package think.thread.c03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class AttemptLocking {
	ReentrantLock lock=new ReentrantLock();
	void untimed(){
		boolean captured=lock.tryLock();
		try {
			System.out.println("trylock():"+captured);
		} finally{
			if(captured){
				lock.unlock();
			}
		}
	}
	
	void timed(){
		boolean captured=false;
		try {
			captured=lock.tryLock(3, TimeUnit.SECONDS);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		try {
			System.out.println("trylock(2,TimeUnit.seconds):"+captured);
		} finally {
			if(captured){
				lock.unlock();
			}
		}
	}
	
	public static void main(String[] args) {
		final AttemptLocking al=new AttemptLocking();
		al.timed();
		al.untimed();
		
		new Thread(){
			{setDaemon(true);}
			public void run() {
				al.lock.lock();
				System.out.println("acquired");
			}
		}.start();
		Thread.yield();
		al.untimed();
		al.timed();
	}
	
}




